package org;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;

public class Game extends BasicGame {

	public BlockMap map;
	public static boolean up,down,right,left;

	public Game() {
		super("test case");
	}


	public void init(GameContainer container) throws SlickException {
		// frame limiter
		container.setVSync(true);
		// load the map (see BlockMap.java)
		map = new BlockMap("data/map02.tmx");
	}


	public void update(GameContainer container, int delta) throws SlickException {
		// cycle trough all entities and execute their update() method
		for (int i = 0; i < BlockMap.entities.size(); i++) {
			LevelObject entity1 = (LevelObject) BlockMap.entities.get(i);
			if (!(entity1 instanceof Block))
				entity1.update(delta);
		}
		// read pressed keys and assign a boolean to them
		if (container.getInput().isKeyDown(Input.KEY_DOWN)) { down  = true; } else { down  = false; }
		if (container.getInput().isKeyDown(Input.KEY_UP))   { up    = true; } else { up    = false; }
		if (container.getInput().isKeyDown(Input.KEY_RIGHT)){ right = true; } else { right = false; }
		if (container.getInput().isKeyDown(Input.KEY_LEFT)) { left  = true; } else { left  = false; }
	}



	

public static int entityCollisionWith(LevelObject entity) throws SlickException {
		// cycle through all entities and execute their isCollisionWith() method
		int ret, col=0;
		
		for (int i = 0; i < BlockMap.entities.size(); i++) {
			LevelObject entity1 = (LevelObject) BlockMap.entities.get(i);
			if ((entity1!=entity)&&(ret=entity.isCollisionWith(entity1))>0) {
				col|=ret; 
			}
		}
		if((col&16)==16)
			entity.onGround=true;
		else
			entity.onGround=false;

		return col;
		// col=0 : pas collsion
		// col=16 :  collision sol
		// col=32 : collision autre chose
	}

	
	
	
	public void render(GameContainer container, Graphics g)  {
		//draw the map
		BlockMap.tmap.render(0, 0);
		//cycle through all entities and execute their draw() method
		for (int i = 0; i < BlockMap.entities.size(); i++) {
			LevelObject entity1 = (LevelObject) BlockMap.entities.get(i);			
			// debug : 
			// need to comment "return true;" in entityCollisionWith() otherwise it won't work 
			// it colorize in red where collision happens .. green for the rest.
			//if (entity1!=BlockMap.joe){
			//	 g.setColor(BlockMap.joe.poly.intersects(entity1.poly) ? Color.red : Color.green);
			//}
			g.draw(entity1.poly);
			entity1.draw(g);				
		}
	}


	public static void main(String[] argv) throws SlickException {
		AppGameContainer container = 
			new AppGameContainer(new Game(), 640, 480, false);
		container.start();
	}
}